import functools

from alibabacloud_ice20201109.client import Client as ICE20201109Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_ice20201109 import models as ice20201109_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient


class AliTryExceptDecorator:
    @staticmethod
    def outer_decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            try:
                result = func(*args, **kwargs)
            except Exception as e:
                result = False, e.message
            return result

        return wrapper

    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        for attr_name, attr_value in cls.__dict__.items():
            if callable(attr_value) and attr_name not in ["__init_subclass__", "outer_decorator"]:
                setattr(cls, attr_name, cls.outer_decorator(attr_value))


class Subtitles(AliTryExceptDecorator):
    @staticmethod
    def create_client() -> ICE20201109Client:
        """
        使用AK&SK初始化账号Client
        @return: Client
        @throws Exception
        """
        # 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        # 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378659.html。
        config = open_api_models.Config(
            # 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。,
            access_key_id="LTAI5t8jMyznaH5dahBisnap",
            # 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。,
            access_key_secret="vQDJGP9D1QIXcFaAIOILrc6OOVIcZz"
        )
        # Endpoint 请参考 https://api.aliyun.com/product/ICE
        config.endpoint = f'ice.cn-hangzhou.aliyuncs.com'
        return ICE20201109Client(config)

    @staticmethod
    def main(
            timeline, video_url
    ) -> None:
        client = Subtitles.create_client()
        submit_media_producing_job_request = ice20201109_models.SubmitMediaProducingJobRequest(
            timeline=f"""{timeline}""",
            output_media_config=f'{video_url}',
            # user_data='{"NotifyAddress":"http://118.31.66.218/api/v1/im/agent/edit-video/callback"}'
            # user_data='{"NotifyAddress":"http://118.31.66.218/api/v1/im/agent/edit-video/callback"}'
        )
        runtime = util_models.RuntimeOptions()
        try:
            # 复制代码运行请自行打印 API 的返回值d
            resp = client.submit_media_producing_job_with_options(submit_media_producing_job_request, runtime)
        except Exception as error:
            # 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            # 错误 message
            print(error.message)
            # 诊断地址
            print(error.data.get("Recommend"))
            UtilClient.assert_as_string(error.message)
        return resp

    @staticmethod
    def make_subtitles(content, font, font_color, font_size, align, border_style, shadow_color, shadow_size,VideoTracks,
                       outline_colour, outline, AudioTracks, x, y, underline, italic, blod,
                       extra_subtitles):

        # 准备一个空的SubtitleTracks列表
        subtitle_tracks = []
        # 定义要循环添加的SubtitleEffects参数列表
        # 循环生成SubtitleTrackClips
        # print(bold)
        # 对字幕轨道 做处理
        for i in range(len(content)):
            # 假设这里是你想要的具体参数
            begin_time = content[i]["begin_time"] / 1000  # 示例：每个的开始时间不同
            end_time = content[i]["end_time"] / 1000  # 示例：每个的结束时间不同
            text = content[i]["text"]  # 示例：每个的文字内容不同
            # 构建SubtitleEffects的结构
            # if subtitle_effects is None:
            #     subtitle_effects_list = []
            #     # 使用上面定义的参数列表
            # else:
            #     subtitle_effects_list = subtitle_effects
            # 构建SubtitleTrackClips的结构，包括SubtitleEffects
            subtitle_clip = {
                "SubtitleTrackClips": [{
                    "TimelineIn": begin_time,
                    "TimelineOut": end_time,
                    "Type": "Text",
                    "Content": text,
                    "X": x,
                    "Y": y,
                    "Font": font,
                    "FontSize": font_size,
                    "FontColor": font_color,
                    "FontFace": {
                        "Bold": blod,
                        "Italic": italic,
                        "Underline": underline,
                    },
                    # 对齐
                    "Alignment": align,
                    # 阴影大小
                    "Shadow": shadow_size,
                    # 阴影颜色
                    "BackColour": shadow_color,
                    # 描边或 边框
                    "Outline": outline,
                    # 描边或底色
                    "OutlineColour": outline_colour,
                    # 1边框加阴影outline_colour  3底色background_color
                    "BorderStyle": border_style
                    # "SubtitleEffects": subtitle_effects_list
                }
                ]
            }
            # 将每个生成的SubtitleTrackClips添加到subtitle_tracks中
            subtitle_tracks.append(subtitle_clip)
        subtitle_tracks.extend(extra_subtitles)
        # print(subtitle_tracks)

        # 构建插入的插入语字幕
        # for item in parenthesis:
        #     for clip in item["SubtitleTrackClips"]:
        #         subtitle_clip["SubtitleTrackClips"].append(clip)
        # print(subtitle_tracks)
        # 构建完整的timeline结
        timeline = {
            "VideoTracks": VideoTracks,
            # 将生成的多个SubtitleTrackClips添加到SubtitleTracks中
            "SubtitleTracks": subtitle_tracks,

            # 额外添加一个字幕轨 来做 插入文字的配置
            "AudioTracks": AudioTracks,

        }

        return timeline
